package com.example.permissionservice.controller;

import com.myprojects.common.pojo.Resource;
import com.myprojects.common.pojo.Role;
import com.example.permissionservice.service.ResourceService;
import com.example.permissionservice.service.RoleResourceRelationService;
import com.example.permissionservice.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myprojects.common.dto.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/role-curd")
public class RoleController {

    @Autowired
    RoleService roleService;

    @Autowired
    RoleResourceRelationService relationService;

    @Autowired
    ResourceService resourceService;

    /**
     * 该方法用于分页查询所有的用户信息(非员工)
     */
    @RequestMapping(value = "/roles",method = RequestMethod.GET)
    @ResponseBody
    public Msg selectRolesByPageNum(
            @RequestParam(value = "pn",defaultValue = "1") Integer pageNum){//普通
        Msg result ;//要返回的结果
        try {
            //在查询之前调用，要设置查询的页数和每页的大小
            PageHelper.startPage(pageNum,10);
            //startPage后紧跟的查询就是一个分页查询
            List<Role> roleList = roleService.selectByExample(null);
            //使用PageInfo包装查询后的结果，需要将pageInfo交给页面
            //将查询出来用户信息加入pageInfo，并连续显示5页
            PageInfo pageInfo = new PageInfo(roleList,5);
            //生成返回成功的结果
            result = Msg.succeed();
            //将pageInfo加入返回的结果中
            result.addData("pageInfo",pageInfo);
//            System.out.println(result.getDataMap());
        }catch (Exception e){
            e.printStackTrace();
            result = Msg.failed();
            result.setMsg("服务端处理异常!");
        }

        return result;
    }

    /**
     * 该方法用于保存角色
     * 前端请求传Json对象则后端使用@RequestParam；
     * 前端请求传Json对象的字符串则后端使用@RequestBody。
     */
    @RequestMapping(value = "/roles",method = RequestMethod.POST)
    @ResponseBody
    public Msg saveRole(@Valid @RequestBody Role role,
//                            @RequestParam(required = false,value = "list[]") List<Integer> resourceIdList,
                            BindingResult result){
        Msg msg = null;
//        System.out.println("传入的role为:"+role+"   resourceIdList:"+role.getResourceIdList());
        //先检查用户信息有没有错误
        Map<String,Object> errorMap = roleService.checkCreateRole(role,result);

        //如果都无误，则尝试保存
        if (errorMap.size() < 1){
            //新建该角色，并返回新建后的id
            int backRoleID = roleService.insertSelective(role);
//            role.setId(backRoleID);
            //新建该角色拥有的资源关系
            relationService.updateRelationByRole(role);
            if (backRoleID > 0){
                msg = Msg.succeed();
                msg.setMsg("保存角色成功！");
            }else {
                msg = Msg.failed();
                msg.setMsg("保存角色失败！");
            }
        }else {
            msg = Msg.failed();
            msg.setMsg("保存角色失败！");
            //将详细错误信息添加进msg
            msg.addData("fieldErrors",errorMap);
        }

        return msg;
    }


    /**
     * 该方法用于删除角色
     */
    @RequestMapping(value = "/roles",method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteRole(@RequestParam(value = "id") Integer id){
        Msg msg = null;

        int iResult = 0;
        int iRelationResult = 0;
        try {
            //删除角色关系
            iRelationResult = relationService.deleteRelationByRoleID(id);
            //删除角色
            iResult = roleService.deleteByPrimaryKey(id);
        }catch (Exception e){
            e.printStackTrace();
        }
        if (iResult > 0){
            msg = Msg.succeed();
            msg.setMsg("删除成功，共删除"+iResult+"个角色");
        }else {
            msg = Msg.failed();
            msg.setMsg("删除失败!");
        }
        return msg;
    }


    /**
     * 该方法用于更新角色
     */
    @RequestMapping(value = "/roles",method = RequestMethod.PUT)
    @ResponseBody
    public Msg updateRole(@Valid @RequestBody Role role, BindingResult result){
        Msg msg = null;

        //先检查用户信息有没有错误
        Map<String,Object> errorMap = roleService.checkUpdateRole(role,result);

        //如果都无误，则尝试保存
        if (errorMap.size() < 1){
            int iResult = 0;
            int iRelationResult = 0;
            try {
                iResult = roleService.updateByPrimaryKeySelective(role);
                relationService.updateRelationByRole(role);
            }catch (Exception e){
                e.printStackTrace();
            }
            if (iResult > 0){
                msg = Msg.succeed();
                msg.setMsg("更新成功，共更新"+iResult+"个角色");
            }else {
                msg = Msg.failed();
                msg.setMsg("更新失败!");
            }
        }else {
            msg = Msg.failed();
            msg.setMsg("更新失败！");
            //将详细错误信息添加进msg
            msg.addData("fieldErrors",errorMap);
        }

        return msg;
    }


    /**
     * 该方法用于获取所有的资源信息
     */
    @RequestMapping(value = "/resources",method = RequestMethod.GET)
    @ResponseBody
    public Msg getAllResources(){
        Msg result ;//要返回的结果
        try {
            List<Resource> resourceList = resourceService.selectAllResource();
            //生成返回成功的结果
            result = Msg.succeed();
            //将pageInfo加入返回的结果中
            result.addData("resourceList",resourceList);
//            System.out.println(result.getDataMap());
        }catch (Exception e){
            e.printStackTrace();
            result = Msg.failed();
            result.setMsg("服务端处理异常!");
        }

        return result;
    }


}
